package com.zzyang.aop.demo.rpc.consumer.netty;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zzyang.aop.demo.rpc.MyReferenceInvocation;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.util.CharsetUtil;

/**
 * TODO
 *
 * @author zhuoziyang
 * @date 2021/5/19 22:38
 */
public class NettyClientChannelHandler extends ChannelInboundHandlerAdapter {

    private volatile ChannelHandlerContext ctx;
    private ChannelPromise promise;

    private String response;


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        this.ctx = ctx;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        response = byteBuf.toString(CharsetUtil.UTF_8);
        promise.setSuccess();

        ctx.close();
    }

    public synchronized ChannelPromise sendMessage(MyReferenceInvocation invocation) throws Exception {
        while (this.ctx == null) {

        }
        String request = JSON.toJSONString(invocation);
        promise = ctx.newPromise();
        ctx.channel().writeAndFlush(Unpooled.copiedBuffer(request, CharsetUtil.UTF_8));
        return promise;
    }

    public <T> T getResponse(Class<T> clazz) {
        return JSONObject.parseObject(response, clazz);
    }

}
